﻿using Language.Resource;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using VisionCloud.Api.Common;
using VisionCloud.Domain.Common;
using VisionCloud.Domain.DtoModel.Sys;
using VisionCloud.Domain.Filters;
using VisionCloud.Service.Sys;
using VisionCloud.Utility.Extensions;
using static VisionCloud.Core.Model.Sys.SysUser;
using AjaxCode = VisionCloud.Domain.Common.AjaxCode;

namespace VisionCloud.Api.Controllers.Sys
{
    /// <summary>
    /// 用户控制器
    /// </summary>
    [SystemModule("用户控制器")]
    [ApiAuthorize(PolicyEnum.RequireRolePermission)]
    [ApiVersion("1.0")]
    [Route("api/sys/[controller]/[Action]")]
    [ApiExplorerSettings(GroupName = "用户控制器")]
    public class UserController : ApiBaseController
    {
        /// <summary>
        /// 用户服务
        /// </summary>
        public UserService UserService { get; set; }

        /// <summary>
        /// 多语言资源
        /// </summary>
        public IStringLocalizer<ControllerResource> localizer { get; set; }

        #region 用户

        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [ApiAuthorize(PolicyEnum.RequireAdmin)]
        [HttpPost]
        public async Task<ApiResult> CreateUser(SysUserDto model)
        {
            model.IP = HttpContext.GetClientUserIp();
            return await TryCatchAsync(UserService.CreateUser(model, TokenModel.YunUserGuid));
        }

        /// <summary>
        /// 通过加密狗获取用户信息并激活设备
        /// </summary>
        /// <param name="usbKeyNODto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GetUserInfo(USBKeyNODto usbKeyNODto)
        {
            var user = OperatorProvider.Get();
            if (user.RoleNameList.Contains("项目管理员"))
            {
                return new ApiResult() { Code = AjaxCode.Error, Message = localizer["YB0037"].Value };
            }
            return await TryCatchAsync(UserService.FindUserByIDAndSetDeviceAtive(user.Id, usbKeyNODto.USBKeyNO));
        }

        /// <summary>
        /// 编辑用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ApiAuthorize(PolicyEnum.RequireCompanyManager)]
        public async Task<ApiResult> EditUser(SysUserDto model)
        {
            return await TryCatchAsync(EditUserBatch(model));
        }

        /// <summary>
        /// 如果账号禁用则下线
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private async Task EditUserBatch(SysUserDto model)
        {
            await UserService.UpdateUser(model, TokenModel.YunUserGuid);
            if (model.Status == EnumUserStatus.禁用)
            {
                List<string> userCodeList = new List<string>() { model.Email, model.PhoneNumber };
                await TryCatchAsync(UserService.Logout(userCodeList));
            }
        }

        /// <summary>
        /// 管理员修改用户密码
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ApiAuthorize(PolicyEnum.RequireAdmin)]
        public async Task<ApiResult> AdminEditPassword(RetrievePwdDto model)
        {
            return await TryCatchAsync(UserService.AdminEditPassword(model.UserCode, model.NewPassword, TokenModel.YunUserGuid));
        }

        /// <summary>
        /// 根据用户ID删除多个用户
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        [HttpPost]
        [ApiAuthorize(PolicyEnum.RequireAdmin)]
        public async Task<ApiResult> DeleteUsers(List<SysUserDto> list)
        {
            return await TryCatchAsync(UserService.DeleteUsers(list, TokenModel.YunUserGuid));
        }

        /// <summary>
        /// 根据用户ID删除用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ApiAuthorize(PolicyEnum.RequireAdmin)]
        public async Task<ApiResult> DeleteUser(SysUserDto model)
        {
            return await TryCatchAsync(UserService.DeleteUser(model.UserId, TokenModel.YunUserGuid));
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GetUser(SysUserDto model)
        {
            if (model.UserId == Guid.Empty && string.IsNullOrEmpty(model.Code))
            {
                model.UserId = TokenModel.YunUserGuid;
            }
            return await TryCatchAsync(UserService.GetUser(model));
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        [HttpPost]
        [ApiAuthorize(PolicyEnum.RequireAdmin)]
        public async Task<ApiResult> GetUserList(SysUserCondition condition)
        {
            condition.UserType = Core.Model.Sys.SysUser.EnumUserType.主账号;
            return await TryCatchAsync(UserService.GetUserPage(condition));
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        [HttpPost]
        [ApiAuthorize(PolicyEnum.RequireAdmin)]
        public async Task<ApiResult> GetCompanyUserList(SysUserCondition condition)
        {
            condition.UserType = Core.Model.Sys.SysUser.EnumUserType.主账号;
            return await TryCatchAsync(UserService.GetCompanyUserPage(condition));
        }

        #endregion 用户

        /// <summary>
        ///  获取用户操作日志
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GetUserLog(LogQueryView logQueryView) => await TryCatchAsync(UserService.GetUserLog(logQueryView));

        #region 激活

        /// <summary>
        /// 新建用户获取 验证码
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public async Task<ApiResult> VerifyCode_Get(RegisterDto request)
        {
            request.IP = HttpContext.GetClientUserIp();
            return await TryCatchAsync(UserService.VerfifyCode_Get(request));
        }

        /// <summary>
        /// 新建用户顺便激活设备
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public async Task<ApiResult> VerifyCode_Check(RegisterDto request) => await TryCatchAsync(UserService.VerifyCode_Check(request));

        /// <summary>
        /// 已有用户进行激活
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public async Task<ApiResult> Activate(RegisterDto request) => await TryCatchAsync(UserService.Activate(request));

        /// <summary>
        /// 更换加密狗后重新激活设备
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public async Task<ApiResult> ReActivate(VerifyDeviceDto request) => await TryCatchAsync(UserService.ReActivate(request));

        /// <summary>
        /// 取消设备与用户绑定
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public async Task<ApiResult> UnActivate(RegisterDto request) => await TryCatchAsync(UserService.UnActivate(request));

        /// <summary>
        /// 验证加密狗是否合法
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public async Task<ApiResult> VerifyDevice(VerifyDeviceDto request) => await TryCatchAsync(UserService.VerifyDevice(request));

        /// <summary>
        /// 获取当前用户信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GetSelf() => await TryCatchAsync(UserService.GetSelf());

        /// <summary>
        /// 修改邮件
        /// </summary>
        /// <param name="registerDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> ChangeEmail(RegisterDto registerDto) => await TryCatchAsync(UserService.ChangeEmail(registerDto));

        /// <summary>
        /// 修改密码,要使用验证码
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> ChangePassWord(ResetDto request) => await TryCatchAsync(UserService.ChangePassWord(request));

        /// <summary>
        /// 云端用户修改密码接口
        /// </summary>
        /// <param name="registerDto"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ApiResult> ResetCloudUserPassword(RegisterDto registerDto) => await TryCatchAsync(UserService.ResetCloudUserPassword(registerDto));

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="registerDto"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ApiResult> ResetPassWord(RegisterDto registerDto) => await TryCatchAsync(UserService.ResetPassWord(registerDto));

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="registerDto"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ApiResult> ResetPassWordFromApp(RegisterDto registerDto) => await TryCatchAsync(UserService.ResetPassWordFromApp(registerDto));

        /// <summary>
        /// 移动端修改密码
        /// </summary>
        /// <param name="registerDto"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ApiResult> ChangePasswordFromApp(RegisterDto registerDto) => await TryCatchAsync(UserService.ChangePasswordFromApp(registerDto));

        /// <summary>
        /// 获取子账户
        /// </summary>
        /// <param name="pageDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GetChildAccountPaged(SysUserPageDto pageDto) => await TryCatchAsync(UserService.GetChildAccountPaged(pageDto));

        /// <summary>
        /// 删除子账户
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> DelChildAccount(JObject obj)
        {
            var userId = obj.GetAndCheck<Guid>("YunUserGuid");
            return await TryCatchAsync(UserService.DelChildAccount(userId));
        }

        /// <summary>
        /// 添加子账户
        /// </summary>
        /// <param name="registerDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> AddChildAccount(RegisterDto registerDto) => await TryCatchAsync(UserService.AddChildAccount(registerDto));

        /// <summary>
        /// 更新子账户
        /// </summary>
        /// <param name="registerDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> UpdateChildAccount(RegisterDto registerDto) => await TryCatchAsync(UserService.UpdateChildAccount(registerDto));

        /// <summary>
        /// 获取加密狗
        /// </summary>
        /// <param name="registerDto"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ApiResult> GetDogUser(RegisterDto registerDto) => await TryCatchAsync(UserService.GetDogUser(registerDto));

        #endregion 激活

        #region

        /// <summary>
        /// 设备excel文档导入
        /// </summary>
        /// <param name="formCollection">excel导入dto</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> ImportExcelToUser(IFormCollection formCollection)
        {
            string ip = HttpContext.GetClientUserIp();
            if (formCollection.Files?.Count > 0)
            {
                return await TryCatchAsync(UserService.ImportExcelFile(formCollection.Files[0], ip));
            }
            else
            {
                return new ApiResult(Domain.Common.AjaxCode.Error, localizer["YB0007"]);
            }
        }

        #endregion

        [HttpPost]
        public async Task<ApiResult> GetDeviceAssign(DeviceAssignDto deviceAssignDto) => await TryCatchAsync(UserService.GetDeviceAssign(deviceAssignDto.userId));

        /// <summary>
        /// 更新用户状态：激活或禁用
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> UpdateUserStatus(SysUserDto model)
        {
            return await TryCatchAsync(UserService.UpdateUserStatus(model, OperatorProvider.Get().YunUserGuid));
        }
    }
}